package org.x.casemodule.service.Impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.x.casemodule.commom.*;
import org.x.casemodule.entity.*;
import org.x.casemodule.mapper.*;
import org.x.casemodule.service.DocumentService;


import org.x.casemodule.commom.TemplateFiller;


import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class DocumentServiceImpl extends ServiceImpl<GeneratedDocumentMapper, GeneratedDocumentEntity> implements DocumentService {

    private final GeneratedDocumentMapper documentRepo;
    private final LegalProvisionMapper lawRepo;
    private final DocumentDraftMapper draftRepo;
    private final DocumentSignatureMapper signRepo;

    private final DocumentTemplateMatcher templateMatcher;
    private final DocumentExporter documentExporter;
    private final DigitalSignatureUtil signatureUtil;

    // 构造函数注入
    public DocumentServiceImpl(GeneratedDocumentMapper documentRepo,
                               LegalProvisionMapper lawRepo,
                               DocumentDraftMapper draftRepo,
                               DocumentSignatureMapper signRepo) {
        this.documentRepo = documentRepo;
        this.lawRepo = lawRepo;
        this.draftRepo = draftRepo;
        this.signRepo = signRepo;
        this.templateMatcher = new DocumentTemplateMatcher();
        this.documentExporter = new DocumentExporter();
        this.signatureUtil = new DigitalSignatureUtil();
    }
//    @Autowired
//    private GeneratedDocumentMapper documentRepo;
//    @Autowired
//    private DocumentTemplateRepository templateRepo;
//    @Autowired
//    private LegalProvisionMapper lawRepo;
//    @Autowired
//    private DocumentDraftMapper draftRepo;
//    @Autowired
//    private DocumentSignatureMapper signRepo;
//    @Autowired
//    private DocumentTemplateMatcher templateMatcher;
//    @Autowired
//    private DocumentExporter documentExporter;
//    @Autowired
//    private DigitalSignatureUtil signatureUtil;

    @Autowired
    private LegalCaseMapper legalCaseMapper;
    @Autowired
    private DocumentTemplateMapper templateRepo;




    @Override
    public GeneratedDocumentEntity generateApplication(String caseId) {
        // 1. 获取案件信息 (伪代码)
        LegalCaseEntity legalCase = getCaseById(caseId);

        // 2. 匹配模板 (使用文档1中的匹配规则)
        String templateName = templateMatcher.matchTemplate((String) legalCase.getType());
        DocumentTemplateEntity template = templateRepo.findByName(templateName)
                .orElseThrow(() -> new RuntimeException("模板不存在: " + templateName + "，案件类型: " + legalCase.getType()));

        // 3. 填充数据生成文书
        String filledContent = TemplateFiller.fillTemplate(template.getTemplateContent(), legalCase);

        // 4. 保存生成的文书
        GeneratedDocumentEntity document = new GeneratedDocumentEntity();
        document.setCaseId(legalCase.getId());
        document.setTemplateId(template.getId());
        document.setDocumentTitle(legalCase.getTitle() + "申请书");
        document.setDocumentContent(filledContent);
        document.setStatus("DRAFT");
        document.setCurrentVersion(1); // 设置初始版本号为1
        document.setSignStatus("UNSIGNED"); // 设置初始签名状态为未签名
        document.setCreateTime(new Date());
        document.setUpdateTime(new Date());
        document.setLastEditTime(new Date());

        documentRepo.insert(document);
        return document;
    }


    // 获取关联的法律条款
    @Override
    public List<document.LegalProvision> getRelatedLaws(Long docId, int position) {
        // 1. 获取文书内容
        GeneratedDocumentEntity document = documentRepo.selectOneById(docId);
        if (document == null) {
            System.out.println("未找到ID为 " + docId + " 的文书");
            throw new RuntimeException("文书不存在");
        }

        // 2. 分析内容提取关键词
        String contentSnippet = extractContentAroundPosition(document.getDocumentContent(), position);
        System.out.println("内容片段：" + contentSnippet);
        List<String> keywords = extractKeywords(contentSnippet);
        System.out.println("提取到的关键词：" + keywords);

        // 3. 查询相关法律条款
        System.out.println("开始查询所有法律条款...");
        List<org.x.casemodule.entity.document.LegalProvision> allLaws = lawRepo.selectAll();
        System.out.println("数据库中法律条款总数：" + allLaws.size());
        // 显示所有法律条款名称
        System.out.println("所有法律条款名称：");
        for (org.x.casemodule.entity.document.LegalProvision law : allLaws) {
            System.out.println("- " + law.getLawName());
        }

        // 过滤匹配的法律条款
        System.out.println("开始过滤匹配的法律条款...");
        List<org.x.casemodule.entity.document.LegalProvision> filteredLaws = new ArrayList<>();
        for (org.x.casemodule.entity.document.LegalProvision law : allLaws) {
            // 修改匹配逻辑：检查法律条款名称是否包含任何关键词
            boolean isMatch = false;
            for (String keyword : keywords) {
                if (law.getLawName().contains(keyword)) {
                    isMatch = true;
                    System.out.println("关键词 '" + keyword + "' 匹配法律条款: " + law.getLawName());
                    break;
                }
            }
            System.out.println("检查法律条款: " + law.getLawName() + " - 匹配: " + isMatch);
            if (isMatch) {
                filteredLaws.add(law);
            }
        }
        System.out.println("匹配的法律条款数量：" + filteredLaws.size());

        // 转换为返回对象
        System.out.println("开始转换法律条款对象...");
        List<document.LegalProvision> result = new ArrayList<>();
        for (org.x.casemodule.entity.document.LegalProvision law : filteredLaws) {
            document.LegalProvision provision = new document.LegalProvision(
                    law.getId(),
                    law.getLawName(),
                    law.getArticle(),
                    law.getClause(),
                    law.getContent()
            );
            result.add(provision);
            System.out.println("转换法律条款: " + law.getLawName());
        }
        System.out.println("最终返回的法律条款数量：" + result.size());
        return result;

//        // 3. 查询相关法律条款
//        return lawRepo.selectAll().stream()
//                .filter(law -> keywords.contains(law.getLawName()))
//                .map(law -> new document.LegalProvision(law.getId(), law.getLawName(), law.getArticle(), law.getClause(), law.getContent()))
//                .toList();

    }

    private List<String> extractKeywords(String content) {
        // 简单的关键词提取实现，按空格分割并过滤常见停用词
        String[] words = content.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", " ")
                .split("\\s+");
        List<String> keywords = new ArrayList<>();
        for (String word : words) {
            if (word.length() > 1) { // 过滤单字符
                keywords.add(word);
            }
        }
        return keywords;
    }


    // 获取文书内容片段
    @Override
    public List<DocumentTemplateEntity> getAllTemplates() {
        return templateRepo.findAllActiveTemplates();
    }

    // 添加模板
    @Override
    public DocumentTemplateEntity addTemplate(DocumentTemplateEntity template) {
        // 设置默认值以避免数据库约束违反
        if (template.getTemplateName() == null || template.getTemplateName().trim().isEmpty()) {
            template.setTemplateName("未命名模板");
        }
        if (template.getCategory() == null) {template.setCategory("APPLICATION");}
        if (template.getCaseTypes() == null) {template.setCaseTypes("[\"CIVIL\"]");}
        if (template.getDescription() == null) { template.setDescription("暂无具体描述"); }

        if (template.getTemplateContent() == null) {
            template.setTemplateContent(""); // 默认内容
        }
        if (template.getTemplateType() == null) {
            template.setTemplateType("CIVIL");
        }
        if (template.getIsActive() == null) {
            template.setIsActive(1); // 默认启用
        }
        if (template.getVersion() == null) {
            template.setVersion(1); // 默认版本号
        }
        //如果有版本号，确认为整数才能通过

        // 设置创建和更新时间
        Date now = new Date();
        template.setCreateTime(now);
        template.setUpdateTime(now);

        templateRepo.insert(template);
        return template;

    }

    // 4. 文书草稿保存接口
    @Override
    public DocumentDraftEntity saveDraft(Long docId, String content) {
        // 获取当前最大版本号
        Integer maxVersion = draftRepo.findMaxVersionByDocId(docId);
        // 处理null值情况，如果还没有草稿，则从0开始
        if (maxVersion == null) {
            maxVersion = 0;
        }
        // 创建新的草稿
        // 保存新草稿 (文档1中的草稿管理规则)
        DocumentDraftEntity draft = new DocumentDraftEntity();
        draft.setDocId(docId);
        draft.setContent(content);
        draft.setVersion(maxVersion + 1);
        draft.setEditorId(getCurrentUserId());
        // 获取当前用户

        return draftRepo.save(draft);
    }

    // 5.文书导出接口
//    @Override
//    public String exportDocument(Long docId, String format) {
//        GeneratedDocumentEntity document = documentRepo.selectOneById(docId);
//        if (document == null) {
//            throw new RuntimeException("文书不存在");
//        }
//        // 根据文档1中的导出规则添加水印
//        String watermark = format.equals("pdf") ?
//                "不可作为正式文件" : "法律援助副本";
//        return documentExporter.export(document.getDocumentContent(), format, watermark);
//    }
    @Override
    public void exportDocument(Long docId, String format, HttpServletResponse response) throws IOException {
        try {
            GeneratedDocumentEntity document = documentRepo.selectOneById(docId);
            if (document == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "文书不存在");
                return;
            }
            // 根据文档1中的导出规则添加水印
            String watermark = format.equals("pdf") ? "不可作为正式文件" : "法律援助副本";
            // 导出文档内容
            String content = document.getDocumentContent();

            // 设置响应头
            String fileName = "document_" + docId + "_" + System.currentTimeMillis() + "." + format.toLowerCase();
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setContentType(getContentTypeByFormat(format));
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + encodedFileName);

            // 使用DocumentExporter将内容直接写入响应流
            documentExporter.exportToStream(content, format, watermark, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (Exception e) {
            throw new IOException("导出文档时发生错误", e);
        }
    }
    private String getContentTypeByFormat(String format) {
        switch (format.toLowerCase()) {
            case "pdf":
                return "application/pdf";
            case "doc":
            case "docx":
                return "application/msword";
            default:
                return "application/octet-stream";
        }
    }

    // 6.文书签名接口
    @Override
    public String signDocument(Long docId, String signImage) {
        GeneratedDocumentEntity document = documentRepo.selectOneById(docId);
        if (document == null) {
            throw new RuntimeException("文书不存在");
        }
//        // 检查签名图片是否为空
//        if (signImage == null || signImage.trim().isEmpty()) {
//            throw new RuntimeException("签名图片不能为空");
//        }
        // 1. 生成数字摘要 (文档1中的防篡改机制)
        String digest = signatureUtil.generateDigitalDigest(document.getDocumentContent());

        // 2. 保存签名记录
        DocumentSignatureEntity signature = new DocumentSignatureEntity();
        signature.setDocId(docId);
        signature.setUserId(getCurrentUserId());
        signature.setSignImage(signImage);
        signature.setDigitalDigest(digest);
        signature.setSignTime(new Date());
        signRepo.insert(signature);

        // 3. 更新文书状态
        document.setSignStatus("SIGNED");
        documentRepo.insert(document);

        // 4. 生成带签名的文档
        return documentExporter.addSignatureToDocument(
                document.getDocumentContent(),
                signImage,
                "pdf");
    }

    // 辅助方法
    private LegalCaseEntity getCaseById(String caseId) {
        // 实际应从案件服务获取
        return legalCaseMapper.selectOneById(Long.valueOf(caseId));
    }

    private Long getCurrentUserId() {

        return cn.dev33.satoken.stp.StpUtil.getLoginIdAsLong();
    }

    private String extractContentAroundPosition(String content, int position) {
        // 实现内容片段提取
        // 修复索引越界问题
        int contentLength = content.length();
        if (position >= contentLength) {
            position = contentLength - 1;
        }
        if (position < 0) {
            position = 0;
        }
        int start = Math.max(0, position - 50);
        int end = Math.min(contentLength, position + 50);
        return content.substring(start, end);

    }
}
